<template>
    <div class="p-4">
      <!-- 搜索行 -->
      <div class="flex gap-4 mb-4">
        生产商名称 <el-input v-model="query.Name" placeholder="请输入生产商名称" clearable style="width: 150px; margin-right: 25px;" />
        联系人 <el-input v-model="query.ContactPerson" placeholder="请输入联系人" clearable style="width: 150px; margin-right: 15px;"  />
        <el-button type="primary" @click="getOutLists()">搜索</el-button>
      </div>
  
      <!-- 功能按钮 -->
      <div style="margin-top: 25px;">
        <el-button type="primary" @click="getOutListes()">查询所有</el-button>
        <el-button type="success" @click="Open()">新增</el-button>
        <el-button type="danger" @click="handleDeleteAll(selectedIds)">删除</el-button>
        <el-button type="warning" >导入</el-button>
        <el-button type="info" @click="batchExport(selectedId)">导出</el-button>
        <el-button type="success" @click="handlePrint()" >打印</el-button>
      </div>
  
      <div>
      <!-- 数据表格 -->
      <el-table ref="printTableRef" :data="tableData"  height="68vh" width="auto" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index"  label="序号"/>
        <el-table-column prop="name" label="生产商名称"  />
        <el-table-column prop="abbreviation" label="简称" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="telephone" label="电话"/>
        <el-table-column prop="contactPerson" label="联系人"/>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column label="状态" width="80">
          <template #default="{row}">
            <el-switch v-model="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button link type="success" size="small" @click="chakan(scope.row)" >查看</el-button>
            <el-button link type="primary" size="small" @click="updates(scope.row)">修改</el-button>
            <el-button link type="danger" size="small" @click="DeleteOut(scope.row.id)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
      v-model:current-page="query.pageindedx"
      v-model:page-size="query.pagesize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />

<!-- 新增生产商弹框 -->
      <el-dialog v-model="dialogVisible" title="生产商信息录入"draggable overflow  :width="responsiveWidth":close-on-click-modal="false" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      @keyup.enter.native="handleSubmit"
    >
      <!-- 基础信息区块 -->
      <div class="form-section">
        <el-form-item label="生产商名称" prop="name" required>
          <el-input  v-model="formData.name"  placeholder="请输入全称"clearable/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="formData.abbreviation" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group  v-model="formData.status"   class="vertical-radio" >
                <el-radio label="正常"  :value="true"  style="margin-right: 20px;"/>
                <el-radio label="停用" :value="false" />
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公司地址" prop="address">
          <el-input v-model="formData.address" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮编" prop="zipCode">
              <el-input  v-model="formData.postalCode"  maxlength="6" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formData.telephone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input  v-model="formData.remarks"  type="textarea" :rows="2"  />
        </el-form-item>
      </div>

      <!-- 分割线 -->
      <el-divider>
        <span class="divider-title">开票信息</span>
      </el-divider>

      <!-- 开票信息区块 -->
      <el-card shadow="never">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="formData.bank" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="account">
              <el-input v-model="formData.accountNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地址电话" prop="addressPhone">
          <el-input v-model="formData.bankAddressPhone" />
        </el-form-item>

        <el-form-item label="纳税人识别号" prop="taxId">
          <el-input v-model="formData.taxId"  maxlength="18" show-word-limit />
        </el-form-item>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button  type="primary" :loading="submitting"  @click="handleSubmit()">确定</el-button>
    </template>
  </el-dialog>
<!-- 查看详情弹框 -->
  <el-dialog v-model="dialogVisible1" title="生产商信息录入"draggable overflow  :width="responsiveWidth":close-on-click-modal="false" >
    <el-form  ref="formRef" :model="formData":rules="formRules"label-position="top" @keyup.enter.native="handleSubmit"  >
      <!-- 基础信息区块 -->
      <div class="form-section">
        <el-form-item label="生产商名称" prop="name" required>
          <el-input  v-model="formData.name"  placeholder="请输入全称"clearable disabled/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="formData.abbreviation" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group  v-model="formData.status"   class="vertical-radio" disabled >
                <el-radio label="正常"  :value="true"  style="margin-right: 20px;"/>
                <el-radio label="停用" :value="false" />
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公司地址" prop="address">
          <el-input v-model="formData.address"  disabled/>
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson"  disabled/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮编" prop="zipCode">
              <el-input  v-model="formData.postalCode"  maxlength="6" show-word-limit  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formData.telephone"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile"  disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input  v-model="formData.remarks"  type="textarea" :rows="2" disabled />
        </el-form-item>
      </div>

      <!-- 分割线 -->
      <el-divider>
        <span class="divider-title">开票信息</span>
      </el-divider>

      <!-- 开票信息区块 -->
      <el-card shadow="never">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="formData.bank" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="account">
              <el-input v-model="formData.accountNumber"disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地址电话" prop="addressPhone">
          <el-input v-model="formData.bankAddressPhone" disabled/>
        </el-form-item>

        <el-form-item label="纳税人识别号" prop="taxId">
          <el-input v-model="formData.taxId"  maxlength="18" show-word-limit disabled />
        </el-form-item>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="guanbi()" type="primary">关闭</el-button>
    
    </template>
  </el-dialog>
<!-- 修改生产商弹框 -->
  <el-dialog v-model="dialogVisible2" title="生产商信息录入"draggable overflow  :width="responsiveWidth":close-on-click-modal="false" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      @keyup.enter.native="handleSubmit"
    >
      <!-- 基础信息区块 -->
      <div class="form-section">
        <el-form-item label="生产商名称" prop="name" required>
          <el-input  v-model="formData.name"  placeholder="请输入全称"clearable/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="formData.abbreviation" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group  v-model="formData.status"   class="vertical-radio" >
                <el-radio label="正常"  :value="true"  style="margin-right: 20px;"/>
                <el-radio label="停用" :value="false" />
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公司地址" prop="address">
          <el-input v-model="formData.address" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮编" prop="zipCode">
              <el-input  v-model="formData.postalCode"  maxlength="6" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formData.telephone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input  v-model="formData.remarks"  type="textarea" :rows="2"  />
        </el-form-item>
      </div>

      <!-- 分割线 -->
      <el-divider>
        <span class="divider-title">开票信息</span>
      </el-divider>

      <!-- 开票信息区块 -->
      <el-card shadow="never">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="formData.bank" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="account">
              <el-input v-model="formData.accountNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地址电话" prop="addressPhone">
          <el-input v-model="formData.bankAddressPhone" />
        </el-form-item>

        <el-form-item label="纳税人识别号" prop="taxId">
          <el-input v-model="formData.taxId"  maxlength="18" show-word-limit />
        </el-form-item>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="quxiao()">取消</el-button>
      <el-button  type="primary" :loading="submitting"  @click="UpdatehandleSubmit()">确定</el-button>
    </template>
  </el-dialog>
    </div>
  </template>
  <script setup>

import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage ,ElMessageBox} from 'element-plus';
import {useRoute,useRouter} from 'vue-router'
import { saveAs } from 'file-saver';
import {KongaUrl} from '@/axios/axiosHelp';
  // 搜索条件
  const query = reactive({
    Name: '',
    ContactPerson: '',
    pageindex:1,
    pagesize:15
  });
const page=reactive({
totalpage:0,
totalcount:0,
  })

  onMounted(()=>{
    getOutLists();
  })
//删除生产商方法
const DeleteOut=(id)=>{
    ElMessageBox.confirm(
    '您确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    KongaUrl({
    url:'/weiwaixie/api/Outsour/DeleteOutSour',
    method:'post',
    data:{
        id:id
    }
})
.then(res=>{
    if(res.data.code==101){
        ElMessage({
        type: 'success',
        message: '操作成功',
      })
        getOutLists();
    }
})

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })

}
//查看详情
const chakan=(row)=>{
    formData.name=row.name
    formData.abbreviation=row.abbreviation
    formData.status=row.status
    formData.address=row.address
    formData.postalCode=row.postalCode
    formData.telephone=row.telephone
    formData.remarks=row.remarks
    formData.contactPerson=row.contactPerson
    formData.mobile=row.mobile
    formData.bank=row.bank
    formData.bankAddressPhone=row.bankAddressPhone
    formData.accountNumber=row.accountNumber
    formData.taxId=row.taxId
    dialogVisible1.value=true;
}
//反填数据并打开修改生产商弹框
const updates=(row)=>{
    formData.id=row.id
    formData.name=row.name
    formData.abbreviation=row.abbreviation
    formData.status=row.status
    formData.address=row.address
    formData.postalCode=row.postalCode
    formData.telephone=row.telephone
    formData.remarks=row.remarks
    formData.contactPerson=row.contactPerson
    formData.mobile=row.mobile
    formData.bank=row.bank
    formData.bankAddressPhone=row.bankAddressPhone
    formData.accountNumber=row.accountNumber
    formData.taxId=row.taxId
    dialogVisible2.value=true;
}
// 修改生产商
const UpdatehandleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    // 这里添加提交逻辑
    KongaUrl({
        url:'/weiwaixie/api/Outsour/UpdateOUtsourc',
        method:'post',
        data:formData
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage.success("修改成功");
            
            formData.name='',
    formData.abbreviation='',
    formData.status=true,
    formData.address='',
    formData.postalCode=''
    formData.telephone=''
    formData.remarks=''
    formData.contactPerson=''
    formData.mobile=''
    formData.bank=''
    formData.bankAddressPhone=''
    formData.accountNumber=''
    formData.taxId=''
    dialogVisible2.value=false;
            getOutLists();
        }
    })
    dialogVisible.value = false
  } catch (error) {
    console.log('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}
// 取消修改生产商 将弹框数据清空
const quxiao=()=>{
    formData.name='',
    formData.abbreviation='',
    formData.status=true,
    formData.address='',
    formData.postalCode=''
    formData.telephone=''
    formData.remarks=''
    formData.contactPerson=''
    formData.mobile=''
    formData.bank=''
    formData.bankAddressPhone=''
    formData.accountNumber=''
    formData.taxId=''
    dialogVisible2.value=false;
}
//清空弹框数据
const guanbi=()=>{
    formData.name='',
    formData.abbreviation='',
    formData.status=true,
    formData.address='',
    formData.postalCode=''
    formData.telephone=''
    formData.remarks=''
    formData.contactPerson=''
    formData.mobile=''
    formData.bank=''
    formData.bankAddressPhone=''
    formData.accountNumber=''
    formData.taxId=''
    dialogVisible1.value=false;
}

  //查询所有数据方法
  const getOutListes=()=>{
    KongaUrl({
        url:'/weiwaidu/api/OutSourc/GetOutSourc',
        method:'get',
        params:{
            Name:null,  
            ContactPerson:null,  
            pageindex:query.pageindex,  
            pagesize:query.pagesize,  
        }
    })
    .then(res=>{
        if(res.status==200){
            console.log(res);
            tableData.value=res.data.list;
            console.log(tableData)
        }
    })
  }

//初始化委外生产商列表
  const getOutLists=()=>{
    KongaUrl({
        url:'/weiwaidu/api/OutSourc/GetOutSourc',
        method:'get',
        params:{
            Name:query.Name,  
            ContactPerson:query.ContactPerson,  
            pageindex:query.pageindex,  
            pagesize:query.pagesize,  
        }
    })
    .then(res=>{
        if(res.status==200){
            console.log(res);
            tableData.value=res.data.list;
            page.totalcount=res.data.totalcount;
            page.totalpage=res.data.totalpage;
            console.log(tableData)
        }
    })
  }
  //翻页函数
  const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  query.pagesize=val;
  getOutLists();
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  query.pageindex=val;
  getOutLists();
}

const selectedIds = ref([])
// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}
// 批量删除操作
const handleDeleteAll = (id) => {
  console.log('选中批量的数据', id.length)
  console.log('选中的数据', id)
  
  if(id.length === 0){
    ElMessage.error("请选择数据")
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${id.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 修正后的请求方式
      const response = await KongaUrl({
        url: '/weiwaixie/api/Outsour/DeleteAll',
        method: 'post',
        data:{
          Id:id
        }
      })
      
      if(response.data.code == 101) {
        ElMessage.success('删除成功')
        // 刷新数据
        getOutLists();
      } 
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}
  // 表格数据
  const tableData = ref([]);

  const dialogVisible = ref(false)
  const dialogVisible1 = ref(false)
  const dialogVisible2 = ref(false)
  //打开新增生产商弹框
  const Open=()=>{
    dialogVisible.value=true;
  }

// 表单数据结构
const formData = reactive({
    id:0,
  name: '',
  abbreviation: '',
  status: true,
  address: '',
  postalCode: '',
  telephone: '',
  remarks: '',
  contactPerson: '',
  mobile: '',
  bank: '',
  bankAddressPhone: '',
  accountNumber: '',
  taxId:'',
  isDelete:0,
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入生产商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  mobile: [
    { 
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
  zipCode: [
    { pattern: /^\d{6}$/, message: '邮编格式不正确', trigger: 'blur' }
  ],
  taxId: [
    { pattern: /^[A-Z0-9]{15,20}$/, message: '税号格式错误', trigger: 'blur' }
  ]
})
// 表单提交处理
const formRef = ref()
const submitting = ref(false)
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    // 这里添加提交逻辑
    KongaUrl({
        url:'/weiwaixie/api/Outsour/AddOutSour',
        method:'post',
        data:formData
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage.success("新增成功");
            dialogVisible.value=false;
            getOutLists();
        }
    })
    dialogVisible.value = false
  } catch (error) {
    console.log('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}
//导出
const batchExport = async () => {
    // 判断 selectedIds 的长度是否为 0
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }

    try {
        const res = await KongaUrl.get('/weiwaidu/api/OutSourc/Daochu', {
            params: {
                // 将参数名改为 Id，与后端保持一致
                Id: selectedIds.value
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '委外生产商列表.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};    
// 定义 ref
const printTableRef = ref(null);
  // 处理表格数据，移除操作列并转换状态列的值
// 处理表格数据，移除操作列并转换状态列的值
const processTableData = (originalData) => {
    return originalData.map(row => {
      const { id,isDelete, operation, ...newRow } = row; // 移除 id 和操作列
        newRow.status = newRow.status ? '启用' : '停用'; // 转换状态列的值
        console.log('要打印的数据',newRow)
        return newRow;
    });
};

// 打印方法
const handlePrint = () => {
    // 创建新窗口用于打印
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
        ElMessage.error('无法打开打印窗口，请检查浏览器设置');
        return;
    }

    // 获取要打印的表格元素（这里假设 tableData 是表格数据数组）
    const originalTableData = tableData.value; 
    const processedTableData = processTableData(originalTableData);

    // 构建打印内容
    printWindow.document.write('<!DOCTYPE html><html><head><title>生产商信息打印</title>');
    printWindow.document.write('<style>');
    // 打印样式设置
    printWindow.document.write('@media print { body { font-size: 12px; } table { border-collapse: collapse; } table, th, td { border: 1px solid black; } }');
    printWindow.document.write('</style></head><body>');
    printWindow.document.write('<table border="1">');
    printWindow.document.write('<thead><tr><th>序号</th><th>生产商名称</th><th>简称</th><th>状态</th><th>地址</th><th>邮编</th><th>电话</th><th>备注</th><th>联系人</th><th>手机号</th><th>开户行</th><th>地址电话</th><th>银行账号</th><th>纳税人识别号</th></tr></thead>');
    printWindow.document.write('<tbody>');
    processedTableData.forEach((row, index) => {
        printWindow.document.write('<tr>');
        printWindow.document.write(`<td>${index + 1}</td>`);
        Object.values(row).forEach(cellValue => {
            printWindow.document.write(`<td>${cellValue}</td>`);
        });
        printWindow.document.write('</tr>');
    });
    printWindow.document.write('</tbody></table>');
    printWindow.document.write('</body></html>');
    printWindow.document.close();

    // 等待页面加载完成后触发打印
    printWindow.onload = () => {
        printWindow.print();
        // 打印完成后关闭窗口
        printWindow.close();
    };
};

  </script>
  <style scoped>
  /* 垂直排列单选组 */
  .vertical-radio :deep(.el-radio) {
    display: block;
    margin: 8px 0;
  }
  
  /* 区块标题样式 */
  .divider-title {
    font-size: 14px;
    color: #606266;
  }
  
  /* 卡片头部优化 */
  .el-card :deep(.el-card__header) {
    padding: 12px 20px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #ebeef5;
  }
  
  /* 表单区块间距 */
  .form-section {
    margin-bottom: 24px;
  }
  </style>